package com.md.util;

import com.google.common.collect.Lists;
import com.md.base.BaseMapper;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * spring工具类,方便在非spring管理环境中获取bean
 *
 * @author 刘骄阳
 * 2021-11-23 16:33
 */
public final class SpringContextUtil {
  private static ApplicationContext context;

  public static <T> T getBean(final Class<T> beanClass) {
    return context.getBean(beanClass);
  }

  public static <T> T getBean(final String name, final Class<T> beanClass) {
    return context.getBean(name, beanClass);
  }

  public static <T> T getBean(final String name) {
    return (T) context.getBean(name);
  }

  public static <T> Map<String, T> getBeansOfType(final @Nullable Class<T> beanClazz) {
    return context.getBeansOfType(beanClazz);
  }

  public static boolean containsBean(final String name) {
    return context.containsBean(name);
  }

  public static String getProfile() {
    return Arrays.stream(context.getEnvironment().getActiveProfiles()).iterator().next();
  }

  public static <T> T getProperty(final String propertyName, final Class<T> clazz) {
    return context.getEnvironment().getProperty(propertyName, clazz);
  }

  public static void init(final ApplicationContext applicationContext) {
    context = applicationContext;
    List<String> list = Lists.newArrayList(((AnnotationConfigServletWebServerApplicationContext) context)
      .getBeanFactory().getBeanNamesIterator()).stream().sorted().collect(Collectors.toList());
    list.forEach(System.out::println);

    // 自动注入BaseMapper
    SqlSessionFactory sqlSessionFactory = getBean(SqlSessionFactory.class);
    Configuration configuration = sqlSessionFactory.getConfiguration();
    configuration.addMapper(BaseMapper.class);
  }


}
